#include "PacketParser.h"

PacketParser::PacketParser(): 
	state_(package_size_1)
{
}

void PacketParser::reset()
{
	state_ = package_size_1;
	package_head_.size = 0;
	m_buffer.clear();
}

bool PacketParser::consume(const uint8 input)
{
	LogFunctionEnter;

	if (package_size_1 == state_)
	{
		package_head_.size = input;
		state_ = package_size_2;
		return false;
	}
	else if (package_size_2 == state_)
	{
		package_head_.size |= uint16(input) << 8;
		state_ = package_cmd_1;
	}
	else if (package_cmd_1 == state_)
	{
		package_head_.cmd = input;
		state_ = package_cmd_2;
	}
	else if (package_cmd_2 == state_)
	{
		package_head_.cmd |= uint16(input) << 8;
		state_ = package_buffer;
	}
	else if (package_buffer == state_)
	{
		m_buffer << uint8(input);
		if (package_head_.size == m_buffer.size() + SIZE_LENGTH + CMD_LENGTH)
		{
			reset();
			return true;
		}

		return false;
	}

	return false;

}